﻿using LJ.AspNetCore.Abstractions.Pack;
using LJ.Host.Abstractions.Pack;
using LJ.Host.Abstractions.Pack.Internal;

namespace LJ.Host.Web.Extensions;

public static class ServiceCollectionExtensions
{
    public static IServiceCollection AddLJ(this IServiceCollection serviceCollection, IConfiguration configuration)
    {
        serviceCollection.AddHttpContextAccessor();
        serviceCollection.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();


        serviceCollection.AddTransient<ICancellationTokenProvider, CancellationTokenProvider>();

        serviceCollection.AddTransient<IConfigProvider, ConfigProvider>();

        serviceCollection.AddTransient<IAppProvider, AppProvider>();


        var packContext = new AspNetCorePackContext(serviceCollection, configuration);

        var packManager = new PackManager(packContext.ReflectionManager);

        serviceCollection.AddSingleton<IPackManager>(packManager);

        //Startup and Hosted 
        serviceCollection.AddSingleton<PackBootstrapper>();
        serviceCollection.AddHostedService(sp => sp.GetRequiredService<PackBootstrapper>());
        serviceCollection.AddSingleton<IPackBootstrapper>(sp => sp.GetRequiredService<PackBootstrapper>());

        foreach (var pack in packManager.GetPacks())
        {
            pack.Add(packContext);
            if (pack is IAspNetCorePack aspNetCorePack)
            {
                aspNetCorePack.Add(packContext);
            }
        }

        return serviceCollection;
    }
}
